<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="模具名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入模具名" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入编码" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <!--       <el-form-item label="图号id" prop="drawingNoId">
        <el-select v-model="queryParams.drawingNoId" placeholder="请选择图号id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <!--       <el-form-item label="部门Id" prop="deptId">
        <el-select v-model="queryParams.deptId" placeholder="请选择部门Id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <!--       <el-form-item label="设备Id" prop="devId">
        <el-select v-model="queryParams.devId" placeholder="请选择设备Id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->

      <el-form-item label="设备" prop="devId">
        <el-select :loading="remortLoading" remote :remote-method="remoteSearch" clearable filterable
          v-model="queryParams.devId" placeholder="请输入至少3个字符搜索设备" class="!w-240px">
          <el-option v-for="dict in equipmentList" :key="dict.id"
            :label="`${dict.equipmentName} - ${dict.code} - ${dict.installPosition}`" :value="dict.id" />
        </el-select>
      </el-form-item>

      <!--   <el-form-item label="总腔数" prop="totalCavity">
        <el-input v-model="queryParams.totalCavity" placeholder="请输入总腔数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="可用腔数" prop="availableCavity">
        <el-input v-model="queryParams.availableCavity" placeholder="请输入可用腔数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="寿命" prop="totalUsageCount">
        <el-input v-model="queryParams.totalUsageCount" placeholder="请输入寿命" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="已使用" prop="usedCount">
        <el-input v-model="queryParams.usedCount" placeholder="请输入已使用" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="预警次数" prop="warningCount">
        <el-input v-model="queryParams.warningCount" placeholder="请输入预警次数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="延期次数" prop="delayCount">
        <el-input v-model="queryParams.delayCount" placeholder="请输入延期次数" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="仓库Id" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库Id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="储位id" prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择储位id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="bom类型" prop="bomCategoryId">
        <el-select v-model="queryParams.bomCategoryId" placeholder="请选择bom类型" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.MOLD_BOM_CATEGORY)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="工步" prop="oprationStep">
        <el-input v-model="queryParams.oprationStep" placeholder="请输入工步" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="数量" prop="quantity">
        <el-input v-model="queryParams.quantity" placeholder="请输入数量" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>

      <el-form-item label="保养类型id" prop="upkeepId">
        <el-select v-model="queryParams.upkeepId" placeholder="请选择保养类型id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="上次保养日期" prop="lastUpkeepTime">
        <el-date-picker v-model="queryParams.lastUpkeepTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="下次保养日期" prop="nextUpkeepTime">
        <el-date-picker v-model="queryParams.nextUpkeepTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="保养人id" prop="upkeeperId">
        <el-select v-model="queryParams.upkeeperId" placeholder="请选择保养人id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="保养日期" prop="upkeepTime">
        <el-date-picker v-model="queryParams.upkeepTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="上次复检日期" prop="lastRecheckTime">
        <el-date-picker v-model="queryParams.lastRecheckTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="下次复检日期" prop="nextRecheckTime">
        <el-date-picker v-model="queryParams.nextRecheckTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="复检人id" prop="recheckerId">
        <el-select v-model="queryParams.recheckerId" placeholder="请选择复检人id" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="复检日期" prop="recheckTime">
        <el-date-picker v-model="queryParams.recheckTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="领用人ID" prop="borrowerId">
        <el-select v-model="queryParams.borrowerId" placeholder="请选择领用人ID" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="领用时间" prop="borrowTime">
        <el-date-picker v-model="queryParams.borrowTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>

      <el-form-item label="归还人ID" prop="returnerId">
        <el-select v-model="queryParams.returnerId" placeholder="请选择归还人ID" clearable class="!w-240px">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="归还时间" prop="returnTime">
        <el-date-picker v-model="queryParams.returnTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['mold:account:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>

        <el-button type="warning" plain @click="handleImport" v-hasPermi="['mold:account:export']">
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['mold:account:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button type="danger" plain :disabled="isEmpty(checkedIds)" @click="handleDeleteBatch"
          v-hasPermi="['mold:account:delete']">
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table row-key="id" v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange" border resizable>
      <el-table-column type="selection" width="55" />
      <el-table-column label="图号" align="center" prop="drawingNo" min-width="100" />
      <el-table-column label="模具名" align="center" prop="name" min-width="300" />
      <el-table-column label="编码" align="center" prop="code" min-width="300" />
      <el-table-column label="库存状态" align="center" prop="inventoryStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_INVENTORY_STATUS" :value="scope.row.inventoryStatus" />
        </template>
      </el-table-column>
      <!--      <el-table-column label="部门" align="center" prop="deptName" /> -->
      <el-table-column label="设备" align="center" prop="devName" min-width="180px">
        <template #default="scope">
          <span>{{ `${scope.row.devName || ''} - ${scope.row.devCode || ''} - ${scope.row.devPosition || ''}` }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总腔数" align="center" prop="totalCavity" />
      <el-table-column label="可用腔数" align="center" prop="availableCavity" />
      <el-table-column label="寿命" align="center" prop="totalUsageCount" />
      <el-table-column label="已使用" align="center" prop="usedCount" />
      <el-table-column label="预警次数" align="center" prop="warningCount" />
      <el-table-column label="延期次数" align="center" prop="delayCount" />
      <!--       <el-table-column label="仓库Id" align="center" prop="warehouseId" />
      <el-table-column label="储位id" align="center" prop="storageId" /> -->
      <el-table-column label="仓库" align="center" prop="warehouseName" min-width="100px" />
      <el-table-column label="储位" align="center" prop="storageName" />
      <el-table-column label="bom类型" align="center" prop="bomCategoryId">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MOLD_BOM_CATEGORY" :value="scope.row.bomCategoryId" />
        </template>
      </el-table-column>
      <el-table-column label="工步" align="center" prop="oprationStep" />
      <!--       <el-table-column label="数量" align="center" prop="quantity" /> -->
      <!--       <el-table-column label="保养类型id" align="center" prop="upkeepId" />
      <el-table-column label="上次保养日期" align="center" prop="lastUpkeepTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="下次保养日期" align="center" prop="nextUpkeepTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="保养人id" align="center" prop="upkeeperId" />
      <el-table-column label="保养日期" align="center" prop="upkeepTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="上次复检日期" align="center" prop="lastRecheckTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="下次复检日期" align="center" prop="nextRecheckTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="复检人id" align="center" prop="recheckerId" />
      <el-table-column label="复检日期" align="center" prop="recheckTime" :formatter="dateFormatter" width="180px" /> -->
      <!--   <el-table-column label="领用人ID" align="center" prop="borrowerId" /> -->
      <!--       <el-table-column label="领用人ID" align="center" prop="borrowerName" />
      <el-table-column label="领用时间" align="center" prop="borrowTime" :formatter="dateFormatter" width="180px" /> -->
      <!--    <el-table-column label="归还人ID" align="center" prop="returnerId" /> -->
      <!--       <el-table-column label="归还人ID" align="center" prop="returnerName" />
      <el-table-column label="归还时间" align="center" prop="returnTime" :formatter="dateFormatter" width="180px" /> -->
      <!--       <el-table-column label="描述" align="center" prop="description" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" align="center" min-width="120px" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['mold:account:update']">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mold:account:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AccountForm ref="formRef" @success="getList" />

  <!-- 导入弹窗 -->
  <importForm ref="importFormRef" @success="getList" />

</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AccountApi, Account } from '@/api/mold/account'
import AccountForm from './AccountForm.vue'
import { EquipmentManageApi, EquipmentManage } from '@/api/business/equipmentmanage'
import importForm from './ImportForm.vue'

/** 模具台账 列表 */
defineOptions({ name: 'Account' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Account[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  drawingNoId: undefined,
  deptId: undefined,
  devId: undefined,
  totalCavity: undefined,
  availableCavity: undefined,
  totalUsageCount: undefined,
  usedCount: undefined,
  warningCount: undefined,
  delayCount: undefined,
  warehouseId: undefined,
  storageId: undefined,
  bomCategoryId: undefined,
  oprationStep: undefined,
  quantity: undefined,
  upkeepId: undefined,
  lastUpkeepTime: [],
  nextUpkeepTime: [],
  upkeeperId: undefined,
  upkeepTime: [],
  lastRecheckTime: [],
  nextRecheckTime: [],
  recheckerId: undefined,
  recheckTime: [],
  borrowerId: undefined,
  borrowTime: [],
  returnerId: undefined,
  returnTime: [],
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const equipmentList = ref<EquipmentManage[]>([])
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AccountApi.getAccountPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const remortLoading = ref(false)
const remoteSearch = async (query) => {
  // 只有当查询关键字长度超过2个字符时才执行搜索
  if (query && query.length > 2) {
    remortLoading.value = true
    let params = {
      keyWords: query
    }
    equipmentList.value = await EquipmentManageApi.getEquipmentManageList(params)
    remortLoading.value = false
  } else {
    // 如果查询关键字为空或长度不足，清空结果列表
    equipmentList.value = []
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AccountApi.deleteAccount(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除模具台账 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await AccountApi.deleteAccountList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch { }
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Account[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AccountApi.exportAccount(queryParams)
    download.excel(data, '模具台账.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
